package org.makcro.sms.services.chat.web.client.mvc;

import java.util.List;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.mvc.view.AllMessagesView;
import org.makcro.sms.services.chat.web.client.services.message.MessageServiceAsync;
import org.makcro.sms.services.chat.web.shared.dto.HistoryItemDto;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class AllMessagesController extends Controller {

	private AllMessagesView		view;
	private MessageServiceAsync	messageServiceAsync;
	private Timer				timer;

	public AllMessagesController() {
		registerEventTypes( AppEvents.LoginSuccessful );
	}

	@Override
	protected void initialize() {
		super.initialize();
		view = new AllMessagesView( this );
		messageServiceAsync = Registry.get( Constants.Services.MessageService );
	}

	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if ( type == AppEvents.LoginSuccessful ) {
			onLoginSuccessful( event );
		}

	}

	private void onLoginSuccessful(AppEvent event) {
		forwardToView( view, event );
//		initTimer( event );
		checkForMessages();
	}

	private void initTimer(AppEvent event) {
		timer = new Timer() {

			@Override
			public void run() {
				checkForMessages();

			}
		};
		timer.scheduleRepeating( 60 * 1000 );
	}

	public void checkForMessages() {
		messageServiceAsync.getAllHistory( new AsyncCallback<List<HistoryItemDto>>() {

			@Override
			public void onSuccess(List<HistoryItemDto> result) {
				AppEvent event = new AppEvent( AppEvents.ALL_MESSAGES_UPDATE, result );
				forwardToView( view, event );
			}

			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);
			}
		} );
	}

}
